package com.ruoyi.web.controller.order;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.req.NormalDTO;
import com.ruoyi.system.service.req.PanelCreateOrderDTO;
import com.ruoyi.system.service.resp.ReplaceDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/11/24
 **/
@Api("点餐台")
@RestController
@RequestMapping("/order/panel")
public class OrderPanelController extends BaseController {
    @Resource
    private BuffetService buffetService;

    @Resource
    private NormalMapper normalMapper;

    @Resource
    private ReplaceMapper replaceMapper;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Resource
    ExampleService exampleService;

    @Resource
    private RestaurantGoodsService restaurantGoodsService;

    @Resource
    private ApproveService approveService;

    @Resource
    private RestaurantStoreResourceService restaurantStoreResourceService;

    @Resource
    private RestaurantOrderService restaurantOrderService;

    @Resource
    BuffetDetailMapper buffetDetailMapper;
    @Resource
    RestaurantOrderDetailMapper restaurantOrderDetailMapper;
    @Resource
    RestaurantOrderMapper restaurantOrderMapper;
    @Resource
    RestaurantOrderDetailService restaurantOrderDetailService;

    @Resource
    private RestaurantCustomerService restaurantCustomerService;

    @Resource
    private RestaurantOrderDetailService detailService;
    @Resource
    private NormalExamineService normalExamineService;

    @Resource
    private NormalExamineDetailService normalExamineDetailService;
    @Resource
    private RestaurantBalanceService restaurantBalanceService;

    @ApiOperation("点餐台获取今日自助餐")
    @Log(title = "点餐台获取今日自助餐", businessType = BusinessType.OTHER)
    @GetMapping("/getTodayBuffet")
    public AjaxResult getTodayBuffet() {
        try {
            Buffet morningBuffet = buffetService.getTodayMorningBuffet();
            if (morningBuffet == null) {
                morningBuffet = new Buffet();
                morningBuffet.setType("早餐");
                morningBuffet.setPrice(new BigDecimal(0));
            }
            Buffet eveningBuffet = buffetService.getTodayEveningBuffet();
            if (eveningBuffet == null) {
                eveningBuffet = new Buffet();
                eveningBuffet.setType("中餐");
                eveningBuffet.setPrice(new BigDecimal(0));
            }
            List<Buffet> todayBuffets = new ArrayList<>();
            todayBuffets.add(morningBuffet);
            todayBuffets.add(eveningBuffet);
            return success(todayBuffets);
        } catch (Exception e) {
            logger.error("点餐台获取今日自助餐失败", e);
            return error("无法获取今日自助餐");
        }
    }

    @ApiOperation("点餐台获取今日点餐菜单")
    @Log(title = "点餐台获取今日点餐菜单", businessType = BusinessType.OTHER)
    @GetMapping("/getTodayNormal")
    public AjaxResult getTodayNormal(Normal normal) {
        logger.info("点餐台获取今日点餐菜单 {}", JSON.toJSONString(normal));
        try {
            if (normal == null) {
                normal = new Normal();
            }
            List<Normal> normals = normalMapper.panelSearch(normal);
            List<NormalDTO> normalDTOS = fillToDTO(normals);
            normalDTOS = normalDTOS.stream()
//                    .filter(n -> "通过".equals(n.getApproveStatus()))
                    .filter(n -> "启用".equals(n.getStatus()))
                    .collect(Collectors.toList());
            return AjaxResult.success(normalDTOS);
        } catch (Exception e) {
            logger.error("点餐台获取今日点餐菜单 出错", e);
            return error("点餐台获取今日点餐菜单失败");
        }

    }

    @ApiOperation("点餐台获取今日代购菜单")
    @Log(title = "点餐台获取今日代购菜单", businessType = BusinessType.OTHER)
    @GetMapping("/getTodayReplace")
    public AjaxResult getTodayReplace(Replace replace) {
        logger.info("点餐台获取今日代购菜单 {}", JSON.toJSONString(replace));
        try {
            if (replace == null) {
                replace = new Replace();
            }
            List<Replace> replaces = replaceMapper.panelSearch(replace);
            List<ReplaceDTO> replaceDTOS = fillReplace(replaces);
            replaceDTOS = replaceDTOS.stream()
//                    .filter(n -> "通过".equals(n.getApproveStatus()))
                    .filter(n -> "启用".equals(n.getStatus()))
                    .collect(Collectors.toList());
            return success(replaceDTOS);
        } catch (Exception e) {
            logger.error("点餐台获取今日代购菜单 出错", e);
            return error("点餐台获取今日代购菜单失败");
        }
    }

    @ApiOperation("点击按钮生成留样管理-桌餐订单 网上订单")
    @Log(title = "点击按钮生成留样管理", businessType = BusinessType.INSERT)
    @PostMapping("/createExamineGoods")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createExamineGoods(@Validated @RequestBody RestaurantOrder query) {
        if (query == null || query.getId() == null) {
            throw new BaseException("生成失败,id传参为空");
        }
        RestaurantOrder restaurantOrder = restaurantOrderMapper.selectById(query.getId());
        if (restaurantOrder == null) {
            throw new BaseException("生成失败,未查询到任何订单" + query.getId());
        }

        List<RestaurantOrderDetail> details = new ArrayList<>();

        RestaurantOrderDetail detail1 = new RestaurantOrderDetail();
        detail1.setNormalId(restaurantOrder.getId());
        List<RestaurantOrderDetail> details1 = restaurantOrderDetailMapper.selectList(detail1);
        if (!CollectionUtils.isEmpty(details1)) {
            details.addAll(details1);
        }

        RestaurantOrderDetail detail2 = new RestaurantOrderDetail();
        detail2.setBuffetId(restaurantOrder.getId());
        List<RestaurantOrderDetail> details2 = restaurantOrderDetailMapper.selectList(detail2);
        if (!CollectionUtils.isEmpty(details2)) {
            details.addAll(details2);
        }

        RestaurantOrderDetail detail3 = new RestaurantOrderDetail();
        detail3.setReplaceId(restaurantOrder.getId());
        List<RestaurantOrderDetail> details3 = restaurantOrderDetailMapper.selectList(detail3);
        if (!CollectionUtils.isEmpty(details3)) {
            details.addAll(details3);
        }

        String area = SecurityUtils.getUserLocation();
        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("位置为全部的用户无法创建");
        }
        if (!CollectionUtils.isEmpty(details)) {
            //新增留样管理
            for (RestaurantOrderDetail detail : details) {
                Example example = new Example();
                example.setGoodsId(detail.getGoodsId());
                example.setSampleTime(new Date());
//                example.setSampleToTime();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(calendar.HOUR_OF_DAY, 48);
                example.setDestroyTime(calendar.getTime());
                example.setSampleNum(new Float(125));
                List<SysDictData> data = dictTypeService.selectDictDataByType("sample_location");
                if (!CollectionUtils.isEmpty(data)) {
                    example.setSampleLocation(data.get(0).getDictValue());
                }
                example.setSaveConditions("冷藏");
                example.setSampleBy(SecurityUtils.getNickName());
                example.setArea(area);
//                example.setImages();
                example.setCreateBy(SecurityUtils.getNickName());
                example.setCreateTime(new Date());
                exampleService.create(example);
            }
        }

        return success();
    }

    @ApiOperation("点击按钮生成留样管理-自助餐菜单")
    @Log(title = "点击按钮生成留样管理", businessType = BusinessType.INSERT)
    @PostMapping("/createBuffetExamineGoods")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createBuffetExamineGoods(@Validated @RequestBody Buffet query) {
        if (query == null || query.getId() == null) {
            throw new BaseException("生成失败,id传参为空");
        }
        Buffet buffet = buffetService.selectById(query.getId());
        if (buffet == null) {
            throw new BaseException("生成失败,未查询到任何自助餐菜单" + query.getId());
        }

        List<BuffetDetail> details = new ArrayList<>();

        BuffetDetail detail1 = new BuffetDetail();
        detail1.setBuffetId(buffet.getId());
        List<BuffetDetail> details1 = buffetDetailMapper.selectList(detail1);
        if (!CollectionUtils.isEmpty(details1)) {
            details.addAll(details1);
        }

        BuffetDetail detail2 = new BuffetDetail();
        detail2.setBuffetId(buffet.getId());
        List<BuffetDetail> details2 = buffetDetailMapper.selectList(detail2);
        if (!CollectionUtils.isEmpty(details2)) {
            details.addAll(details2);
        }

        BuffetDetail detail3 = new BuffetDetail();
        detail3.setBuffetId(buffet.getId());
        List<BuffetDetail> details3 = buffetDetailMapper.selectList(detail3);
        if (!CollectionUtils.isEmpty(details3)) {
            details.addAll(details3);
        }

        String area = SecurityUtils.getUserLocation();
        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("位置为全部的用户无法创建");
        }
        if (!CollectionUtils.isEmpty(details)) {
            //新增留样管理
            for (BuffetDetail detail : details) {
                Example example = new Example();
                example.setGoodsId(detail.getGoodsId());
                example.setSampleTime(new Date());
//                example.setSampleToTime();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(calendar.HOUR_OF_DAY, 48);
                example.setDestroyTime(calendar.getTime());
                example.setSampleNum(new Float(125));
                List<SysDictData> data = dictTypeService.selectDictDataByType("sample_location");
                if (!CollectionUtils.isEmpty(data)) {
                    example.setSampleLocation(data.get(0).getDictValue());
                }
                example.setSaveConditions("冷藏");
                example.setSampleBy(SecurityUtils.getNickName());
                example.setArea(area);
//                example.setImages();
                example.setCreateBy(SecurityUtils.getNickName());
                example.setCreateTime(new Date());
                exampleService.create(example);
            }
        }

        return success();
    }

    @ApiOperation("点餐台下单")
    @Log(title = "点餐台下单", businessType = BusinessType.INSERT)
    @PostMapping("/createOrder")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createOrder(@Validated @RequestBody PanelCreateOrderDTO panelCreateOrderDTO) {
        RestaurantCustomer customer = restaurantCustomerService.getCustomerByUserId(panelCreateOrderDTO.getPayerId().toString());
        if (customer.getBalance().compareTo(panelCreateOrderDTO.getPrice()) == -1) {
            return AjaxResult.error("余额不足，请充值后重试！");
        }
        if ("normal".equals(panelCreateOrderDTO.getType())) {
            handleNormal(panelCreateOrderDTO);
        } else if ("buffet".equals(panelCreateOrderDTO.getType())) {
            handleBuffet(panelCreateOrderDTO);
        } else if ("replace".equals(panelCreateOrderDTO.getType())) {
            handleReplace(panelCreateOrderDTO);
        }
        return success();
    }

    private void handleNormal(PanelCreateOrderDTO panelCreateOrderDTO) {
        //创建订单
        RestaurantOrder restaurantOrder = new RestaurantOrder();
//        restaurantOrder.setPeopleCount(panelCreateOrderDTO.getBuffetCount());
        restaurantOrder.setCustomerId(panelCreateOrderDTO.getPayerId());
        RestaurantCustomer customerByUserId = restaurantCustomerService.getCustomerByUserId(panelCreateOrderDTO.getPayerId() + "");
        restaurantOrder.setCustomerName(customerByUserId.getCustomerName());
        restaurantOrder.setType(panelCreateOrderDTO.getType());
        restaurantOrder.setStatus("待确定");
        restaurantOrder.setArea(SecurityUtils.getUserLocation());
        restaurantOrder.setOrderTime(new Date());
        restaurantOrder.setAmount(panelCreateOrderDTO.getPrice());
        restaurantOrder.setOrderNum(BaseController.createBusinessNum("NOR"));
        restaurantOrder.setCreateBy(SecurityUtils.getNickName());
        restaurantOrderService.createNormalOrder(restaurantOrder);
        //创建明细
        for (Normal normal : panelCreateOrderDTO.getNormals()) {
            RestaurantOrderDetail detail = new RestaurantOrderDetail();
            detail.setOrderId(restaurantOrder.getId());
            detail.setNormalId(normal.getId());
            detail.setGoodsId(normal.getGoodsId());
            detail.setCount(normal.getCount());
            detail.setCreateBy(SecurityUtils.getNickName());
            detail.setPrice(normal.getPrice());
            detailService.createNormalDetailOrder(detail);
        }
//        handleExamine(restaurantOrder.getId());
    }

    public void handleExamine(Long orderId) {
        RestaurantOrder restaurantOrder = restaurantOrderService.selectNormalOrderById(orderId);
        if (restaurantOrder == null) {
            return;
        }
        // 非点餐订单不需要创建质检   点餐网上订单也需要生成
        if (!restaurantOrder.getType().contains("点餐网上订单")) {
            if (!restaurantOrder.getType().contains("normal")) {
                return;
            }
        }
        // 获取订单明细
        List<RestaurantOrderDetail> restaurantOrderDetails = detailService.getNormalOrderDetailList(RestaurantOrderDetail.builder()
                .orderId(orderId).build());
        if (CollectionUtils.isEmpty(restaurantOrderDetails)) {
            return;
        }
        List<Long> normalIds = restaurantOrderDetails.stream().map(RestaurantOrderDetail::getNormalId).collect(Collectors.toList());
        List<Normal> normals = normalMapper.selectByIds(normalIds);
        Set<Long> goodIds = normals.stream().map(Normal::getGoodsId).collect(Collectors.toSet());
        // 获取质检单明细
        NormalExamine normalExamine = new NormalExamine();
        normalExamine.setOrderId(restaurantOrder.getId());
        normalExamine.setStatus("质检待完成");
        normalExamine.setCreateBy(SecurityUtils.getNickName());
        normalExamineService.create(normalExamine);
        List<NormalExamineDetail> normalExamineDetails = normalExamineDetailService.selectList(NormalExamineDetail.builder()
                .examineId(normalExamine.getId()).build());
        Map<Long, NormalExamineDetail> goodsIdExamineDetailMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(normalExamineDetails)) {
            goodsIdExamineDetailMap = normalExamineDetails.stream()
                    .filter(n -> n.getGoodsId() != null)
                    .collect(Collectors.toMap(NormalExamineDetail::getGoodsId, n -> n, (a1, a2) -> a1));
        }
        // 没有的创建
        for (Long goodsId : goodIds) {
            if (goodsIdExamineDetailMap.get(goodsId) != null) {
                continue;
            }
            NormalExamineDetail examineDetailCreate = new NormalExamineDetail();
            examineDetailCreate.setExamineId(normalExamine.getId());
            examineDetailCreate.setGoodsId(goodsId);
            examineDetailCreate.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            normalExamineDetailService.create(examineDetailCreate);
        }
        // 多余的删除
        for (Long goodsId : goodsIdExamineDetailMap.keySet()) {
            if (goodIds.contains(goodsId)) {
                continue;
            }
            NormalExamineDetail examineDetail = goodsIdExamineDetailMap.get(goodsId);
            normalExamineDetailService.deleteById(examineDetail.getId());
        }
    }

    private void handleBuffet(PanelCreateOrderDTO panelCreateOrderDTO) {
        RestaurantOrder restaurantOrder = new RestaurantOrder();
        restaurantOrder.setPeopleCount(panelCreateOrderDTO.getBuffetCount());
        restaurantOrder.setCustomerId(panelCreateOrderDTO.getPayerId());
        RestaurantCustomer customerByUserId = restaurantCustomerService.getCustomerByUserId(panelCreateOrderDTO.getPayerId() + "");
        restaurantOrder.setCustomerName(customerByUserId.getCustomerName());
        restaurantOrder.setType(panelCreateOrderDTO.getType());
        restaurantOrder.setStatus("待确定");
        restaurantOrder.setArea(SecurityUtils.getUserLocation());
        restaurantOrder.setOrderTime(new Date());
        restaurantOrder.setAmount(panelCreateOrderDTO.getPrice());
        restaurantOrder.setOrderNum(BaseController.createBusinessNum("BUF"));
        restaurantOrder.setCreateBy(SecurityUtils.getNickName());
        restaurantOrderService.createNormalOrder(restaurantOrder);

    }

    private void handleReplace(PanelCreateOrderDTO panelCreateOrderDTO) {
        //创建订单
        RestaurantOrder restaurantOrder = new RestaurantOrder();
//        restaurantOrder.setPeopleCount(panelCreateOrderDTO.getBuffetCount());
        restaurantOrder.setCustomerId(panelCreateOrderDTO.getPayerId());
        RestaurantCustomer customerByUserId = restaurantCustomerService.getCustomerByUserId(panelCreateOrderDTO.getPayerId() + "");
        restaurantOrder.setCustomerName(customerByUserId.getCustomerName());
        restaurantOrder.setType(panelCreateOrderDTO.getType());
        restaurantOrder.setStatus("待确定");
        restaurantOrder.setArea(SecurityUtils.getUserLocation());
        restaurantOrder.setOrderTime(new Date());
        restaurantOrder.setAmount(panelCreateOrderDTO.getPrice());
        restaurantOrder.setOrderNum(BaseController.createBusinessNum("REP"));
        restaurantOrder.setCreateBy(SecurityUtils.getNickName());
        restaurantOrderService.createNormalOrder(restaurantOrder);
        //创建明细
        for (Replace normal : panelCreateOrderDTO.getReplaces()) {
            RestaurantOrderDetail detail = new RestaurantOrderDetail();
            detail.setOrderId(restaurantOrder.getId());
            detail.setReplaceId(normal.getId());
            detail.setGoodsId(normal.getResourceId());
            detail.setCount(normal.getCount());
            detail.setCreateBy(SecurityUtils.getNickName());
            detail.setPrice(normal.getPrice());
            detailService.createNormalDetailOrder(detail);
        }
    }

    private List<ReplaceDTO> fillReplace(List<Replace> replaces) {
        if (CollectionUtils.isEmpty(replaces)) {
            return Collections.emptyList();
        }
        List<Long> resourceIds = replaces.stream().filter(Objects::nonNull).map(Replace::getResourceId).collect(Collectors.toList());
        List<RestaurantStoreResource> restaurantStoreResources = restaurantStoreResourceService.selectRestaurantStoreResourceByIds(resourceIds);
        Map<Long, RestaurantStoreResource> resourceMap;
        if (!CollectionUtils.isEmpty(restaurantStoreResources)) {
            resourceMap = restaurantStoreResources.stream().collect(Collectors.toMap(RestaurantStoreResource::getId, r -> r));
        } else {
            resourceMap = new HashMap<>();
        }
        List<ReplaceDTO> replaceDTOS = replaces.stream().filter(Objects::nonNull).map(r -> {
            ReplaceDTO replaceDTO = new ReplaceDTO();
            replaceDTO.setId(r.getId());
            replaceDTO.setResourceId(r.getResourceId());
            replaceDTO.setResourceName(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getName).orElse(null));
            replaceDTO.setName(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getName).orElse(null));
            replaceDTO.setImage(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getImageUrl).orElse(null));
            replaceDTO.setType(r.getType());
            replaceDTO.setPrice(r.getPrice());
            replaceDTO.setUnit(r.getUnit());
            replaceDTO.setStatus(r.getStatus());
            replaceDTO.setCreateBy(r.getCreateBy());
            replaceDTO.setCreateTime(r.getCreateTime());
            replaceDTO.setUpdateBy(r.getUpdateBy());
            replaceDTO.setUpdateTime(r.getUpdateTime());
//            ApproveMission approveMission = approveService.getApproveMissionByActivityd(r.getId(), "代购菜单审批");
//            if (approveMission == null) {
            replaceDTO.setApproveStatus("通过");
//            } else {
//                replaceDTO.setApproveStatus(approveMission.getStatus());
//                replaceDTO.setApproveMissionId(approveMission.getId());
//            }
            replaceDTO.setCount(0);
            return replaceDTO;
        }).filter(r -> "启用".equals(r.getStatus())).filter(r -> "通过".equals(r.getApproveStatus())).collect(Collectors.toList());

        return replaceDTOS;
    }

    private List<NormalDTO> fillToDTO(List<Normal> normals) {
        if (CollectionUtils.isEmpty(normals)) {
            return new ArrayList<>();
        }
        return normals.stream().map(g -> {
            NormalDTO normalDTO = new NormalDTO();
            normalDTO.setId(g.getId());
            normalDTO.setPrice(g.getPrice());
            normalDTO.setGoodsId(g.getGoodsId());
            normalDTO.setStatus(g.getStatus());
            normalDTO.setName(g.getName());
            normalDTO.setHot(g.getHot());
            normalDTO.setImage(g.getImage());
//            ApproveMission approveMission = approveService.getApproveMissionByActivityd(g.getId(), "点餐菜单审批");
//            if (approveMission == null) {
            normalDTO.setApproveStatus("通过");
//            } else {
//                normalDTO.setApproveStatus(approveMission.getStatus());
//                normalDTO.setApproveMissionId(approveMission.getId());
//            }
            normalDTO.setCreateBy(g.getCreateBy());
            normalDTO.setCreateTime(g.getCreateTime());
            normalDTO.setUpdateBy(g.getUpdateBy());
            normalDTO.setUpdateTime(g.getUpdateTime());
            normalDTO.setRemark(g.getRemark());
            normalDTO.setCount(0);
            return normalDTO;
        }).filter(n -> "通过".equals(n.getApproveStatus())).filter(n -> "启用".equals(n.getStatus())).collect(Collectors.toList());
    }

    @ApiOperation("获取自助餐订单")
    @Log(title = "获取自助餐订单", businessType = BusinessType.OTHER)
    @GetMapping("/getOrderList")
    public TableDataInfo getOrderList(String orderNum, String orderType, String area) {
        RestaurantOrder restaurantOrder = new RestaurantOrder();
        restaurantOrder.setType(orderType);
        restaurantOrder.setOrderNum(orderNum);
        restaurantOrder.setArea(area);
        startPage();
        List<RestaurantOrder> normalOrderList = restaurantOrderService.getNormalOrderList(restaurantOrder);
        return getDataTable(normalOrderList);
    }

    @ApiOperation("确认订单")
    @Log(title = "确认订单", businessType = BusinessType.OTHER)
    @GetMapping("/confirmOrder")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult confirmOrder(String orderNum, String orderType) {
        RestaurantOrder restaurantOrder = new RestaurantOrder();
        restaurantOrder.setType(orderType);
        restaurantOrder.setOrderNum(orderNum);
        List<RestaurantOrder> normalOrderList = restaurantOrderService.getNormalOrderList(restaurantOrder);
        if (CollectionUtils.isEmpty(normalOrderList)) {
            return AjaxResult.error("订单不存在");
        }
        RestaurantOrder order = normalOrderList.get(0);
        order.setStatus("已送达");
        order.setUpdateBy(SecurityUtils.getNickName());
        order.setUpdateTime(new Date());

        //用户金额扣费
        RestaurantCustomer customer = restaurantCustomerService.getCustomerByUserId(order.getCustomerId().toString());
        if (customer.getBalance().compareTo(order.getAmount()) == -1) {
            return AjaxResult.error("余额不足，请充值后重试！");
        }
        //上次金额
        order.setLastMoney(customer.getBalance());
        //扣费
        customer.setBalance(customer.getBalance().subtract(order.getAmount()));
        //本次金额
        order.setNowMoney(customer.getBalance());
        restaurantCustomerService.updateCustomerByUserId(customer);
        restaurantOrderService.updateNormalOrder(order);

        //创建消费记录
        RestaurantBalanceDetail restaurantBalanceDetail = new RestaurantBalanceDetail();
        restaurantBalanceDetail.setType("用户消费");
        restaurantBalanceDetail.setLocation(SecurityUtils.getUserLocation());
        restaurantBalanceDetail.setAmount(order.getAmount());
        restaurantBalanceDetail.setCustomerId(order.getCustomerId());
        restaurantBalanceDetail.setCreateBy(SecurityUtils.getNickName());
        if ("normal".equals(order.getType())) {
            restaurantBalanceDetail.setReason("点餐订单[" + order.getOrderNum() + "]消费");
        } else if ("buffet".equals(order.getType())) {
            restaurantBalanceDetail.setReason("自助餐订单[" + order.getOrderNum() + "]消费");
        } else if ("replace".equals(order.getType())) {
            restaurantBalanceDetail.setReason("代购订单[" + order.getOrderNum() + "]消费");
        }
        restaurantBalanceService.create(restaurantBalanceDetail);
        handleExamine(order.getId());
        return AjaxResult.success();
    }
}
